﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Text;
using Twipler.App.DataDoc;
using Twipler.App.Parse;
using Twipler.App.Machine;

namespace Twipler.App.Render.Tree
{
    public class DelayItem : AbstractItem
    {
        private AbstractItem _delayedPart;
        private AbstractItem _waitingPart;
        private string _queryString;
        private List<Instruction> _repeatIf;

        public override List<AbstractItem> Children { get { return new List<AbstractItem>() { _delayedPart }; } }

        public static DelayItem Create(AbstractItem delayedPart, AbstractItem waitingPart, string queryString, List<Instruction> repeatIf)
        {
            return new DelayItem()
                       {
                           _delayedPart = delayedPart,
                           _waitingPart = waitingPart,
                           _queryString = queryString,
                           _repeatIf = repeatIf
                       };
        }

        public override string PostbackId
        {
            get
            {
                return GetHashCode().ToString();
            }
        }

        public override void Render(System.Text.StringBuilder html, App.Machine.Environment environment)
        {
            string randomKey = RandomString(8);

            html.Append("<script>$.get('async.aspx?cmd=delay&id=" + PostbackId + "&" + _queryString + "', function(data) { $('.result_" + randomKey + "').html(data);});</script>");

            html.Append("<div class='result_" + randomKey + "'>");

            if (_waitingPart != null)
                _waitingPart.Render(html, environment);

            html.Append("</div>");
        }

        public void RenderChild(StringBuilder html, Machine.Environment environment)
        {
            if (_delayedPart == null)
                return;

            _delayedPart.Render(html, environment);

            if (_repeatIf != null)
            {
                object var = environment.Execute(_repeatIf);
                if ((var != null) && (var is bool) && ((bool)var))
                    Render(html, environment);                
            }
        }
    }

}